<template>
    <view>
        <view class="logo">
            <img src="../../static/logo.png"></img>
        </view>
        <view class="body">
            <view class="bodyIn">
                <img src="../../static/images/icon/icon_username.png"><img />
                <input class="user" placeholder="请输入账号" @input="bindUser" placeholder-class="padding-left:20rpx">
            </view>
            <view class="bodyIn">
                <img src="../../static/images/icon/icon_password.png"><img />
                <input class="user" placeholder="请输入密码" password="true" @input="bindPassword">
            </view>
        </view>

        <foot>
            <view class="login">
                <button class="loging1" @tap="bindLogin">登录</button>
            </view>
            <view class="wxlogin">
                <button class="loging" open-type="getUserInfo" type='primary' withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">微信登录</button>
            </view>
            <!-- <view class="wxlogin">
                <button class="loging" @tap="bindAdmin">不含任何逻辑</button>
            </view> -->

            <!-- <form @submit="formSubmit" report-submit='true'>
                <button form-type="submit">Submit</button>
            </form> -->

        </foot>
    </view>
</template>

<script>
//导入封装请求的模块
import {
    request
} from "../../comon/js/request.js";

export default {
    data() {
        return {
            loginfrom: {
                username: "",
                password: ""
            },
            formId: 123,
            SessionKey: '',
            openid: "",
            nickName: null,
            avatarUrl: null,
            // isCanUse: uni.getStorageSync('isCanUse') || true //默认为true
            isCanUse: uni.getStorageSync('isCanUse') //默认为true
        };
    },
    //默认加载
    onShow() {
        // this.login();
        uni.hideHomeButton()
    },
    methods: {
        //测试登陆
        bindAdmin() {
            uni.showToast({
                title: "不含任何逻辑",
                icon: 'none',
                duration: 2000
            });
        },
        bindUser(event) {
            this.loginfrom.username = event.target.value;
            // console.log(this.loginfrom.username);
        },
        bindPassword(event) {
            this.loginfrom.password = event.target.value;
            // console.log(this.loginfrom.password);
        },

        bindLogin() {
            console.log("登陆")
            let that = this;
            if (that.loginfrom.username === "" || that.loginfrom.password === "") {
                return;
            }
            uni.request({
                // url: "http://yaolu.dev.lanlnk.com/platform/v1/passport/login",
                url: "https://yl.solid-cn.com/platform/v1/passport/login",
                method: "POST",
                data: {
                    username: that.loginfrom.username,
                    password: that.loginfrom.password
                },
                success: (res) => {
                    console.log(res)
                    uni.showToast({
                        title: "登陆中...",
                        icon: 'none',
                        duration: 2000
                    });
                    uni.setStorageSync('token', res.data.result.access_token)
                    if (res.data.errorCode === 0) {
                        // uni.setStorageSync('token', res.data.result.access_token)
                        // console.log(res.data.result.access_token, "----------------------")
                        request({
                            url: "v1/passport/detail"
                        }).then(res => {
                            uni.switchTab({
                                url: "../index/index"
                            })
                            // console.log('success_^^^^^^^^^^^^^^^^^^^^', res);
                            uni.setStorageSync("role_grade", res.data.result.role_grade)
                            uni.setStorageSync("useMsg", res.data.result.id)
                            // uni.setStorageSync("wx_openid", res.data.result.wx_openid)
                            uni.setStorage({
                                key: 'wx_openid',
                                data: res.data.result.wx_openid,
                                success: function () {
                                    uni.setStorageSync("isLogin", true)
                                    uni.switchTab({
                                        url: "../index/index",
                                        success(res) {
                                            let page = getCurrentPages().pop();
                                            if (page == undefined || page == null) {
                                                return
                                            }
                                            page.onLoad();
                                        }
                                    })
                                }
                            })
                        })
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                fail: (error) => {
                    console.log(JSON.stringify(error))
                    uni.showToast({
                        title: JSON.stringify(error),
                        icon: 'none',
                    });
                }

            })
        },

        //微信授权
        //第一授权获取用户信息===》按钮触发
        wxGetUserInfo() {
            let _this = this;
            //获取微信的授权的信息
            uni.getUserInfo({
                provider: 'weixin',
                success: function (infoRes) {
                    let userInfo = infoRes.userInfo.userInfo
                    let nickName = infoRes.userInfo.nickName; //昵称
                    let avatarUrl = infoRes.userInfo.avatarUrl; //头像
                    let gender = infoRes.userInfo.gender //性别
                    let province = infoRes.userInfo.province
                    let city = infoRes.userInfo.city
                    let county = infoRes.userInfo.county
                    // console.log(infoRes, "微信收集到的信息")
                    uni.setStorageSync("wxImg", avatarUrl)
                    // console.log(getStorageSync("wxImg"),"/////////////")
                    // try {
                    //     uni.setStorageSync('isCanUse', false); //记录是否第一次授权 false:表示不是第一次授权
                    //     // _this.updateUserInfo();
                    // } catch (e) {
                    //     // console.log(e,":::::::::::::::::::")
                    // }
                    uni.login({
                        provider: 'weixin',
                        success: function (res) {
                            uni.showLoading({
                                title: '登陆中...',
                            });
                            console.log(res, ".....................")
                            uni.request({
                                url: 'https://yl.solid-cn.com/wechat/v1/user/wxLogin',
                                data: {
                                    code: res.code,
                                },
                                method: 'GET',
                            }).then(res => {
                                console.log(res, "这里这里这里``````````")
                                if (res[1].data.errorCode == 0) {
                                    //openId、或SessionKdy存储//隐藏loading
                                    console.log(res[1].data.result.access_token);
                                    uni.setStorage({
                                        key: 'token',
                                        data: res[1].data.result.access_token,
                                        success: function () {
                                            let token = uni.getStorageSync("token");
                                            request({
                                                url: "v1/passport/detail",
                                                // header: {
                                                //     Accept: "application/json",
                                                //     Authorization: `Bearer ${res[1].data.result.access_token}`
                                                // }
                                            }).then(res => {
                                                // console.log('success_^^^^^^^^^^^^^^^^^^^^', res);
                                                uni.setStorageSync("role_grade", res.data.result.role_grade)
                                                uni.setStorageSync("useMsg", res.data.result.id)
                                                uni.setStorage({
                                                    key: 'wx_openid',
                                                    data: res.data.result.wx_openid,
                                                    success: function () {
                                                        uni.switchTab({
                                                            url: "../index/index",
                                                            success(res) {
                                                                uni.hideLoading();
                                                                let page = getCurrentPages().pop();
                                                                if (page == undefined || page == null) {
                                                                    return
                                                                }
                                                                page.onLoad();
                                                            }
                                                        })
                                                    }
                                                })
                                            })
                                        }
                                    })
                                } else if (res[1].data.errorCode == 403) {
                                    // console.log("未绑定微信")
                                    uni.hideLoading();
                                    uni.showModal({
                                        title: res[1].data.message,
                                        showCancel: false,
                                        // content: '是否需要退出',    
                                        // success: function (res) {
                                        //     if (res.confirm) {

                                        //     }
                                        // }
                                    });
                                } else {
                                    uni.hideLoading();
                                }
                                // uni.setStorageSync("session_key", res.data.result.session_key)
                                // 暂时跳转
                            })
                        }
                    })
                },
                fail(res) {}
            });
        },

        //登录
        login() {
            // this.wxGetUserInfo()
            let _this = this;
            uni.showLoading({
                title: '登录中...'
            });
            // 1.wx获取登录用户code
            uni.login({
                provider: 'weixin',
                success: function (loginRes) {
                    console.log(loginRes)
                    let code = loginRes.code;
                    uni.hideLoading();
                    uni.getSetting({
                        success(res) {
                            // console.log(res.authSetting,"看反悔啊啊啊啊啊啊啊啊啊啊啊啊")
                            let authSetting = res.authSetting
                        }
                    })
                    if (_this.authSetting == "") {
                        return
                    } else if (_this.authSetting !== {}) {
                        request({
                            url: 'v1/wechat/wxLogin',
                            data: {
                                code: _this.code,
                            },
                            method: 'GET',
                        }).then(res => {
                            // console.log(res, "onloadonloadoonloadonloado``````````")
                            //openId、或SessionKdy存储//隐藏loading
                            uni.setStorageSync("openid", res.data.result.openid)
                            uni.setStorageSync("session_key", res.data.result.session_key)
                            // 暂时跳转
                            if (res.data.errorCode === 0) {
                                uni.switchTab({
                                    url: "../index/index"
                                })
                            }
                        })
                        //非第一次授权获取用户信息
                        // uni.getUserInfo({
                        //     // provider: 'weixin',
                        //     // success: function (infoRes) {
                        //     //     //获取用户信息后向调用信息更新方法
                        //     //     let nickName = infoRes.userInfo.nickName; //昵称
                        //     //     let avatarUrl = infoRes.userInfo.avatarUrl; //头像
                        //     //     // _this.updateUserInfo(); //调用更新信息方法
                        //     // }
                        // });
                        // return
                    }
                    //2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息

                }
            });
        },
        //向后台更新信息
        // updateUserInfo() {
        //     let _this = this;
        //     uni.request({
        //         url: 'url', //服务器端地址
        //         data: {
        //             appKey: this.$store.state.appKey,
        //             customerId: _this.customerId,
        //             nickName: _this.nickName,
        //             headUrl: _this.avatarUrl
        //         },
        //         method: 'POST',
        //         header: {
        //             'content-type': 'application/json'
        //         },
        //         success: (res) => {
        //             if (res.data.state == "success") {
        //                 uni.reLaunch({ //信息更新成功后跳转到小程序首页
        //                     url: '/pages/index/index'
        //                 });
        //             }
        //         }
        //     });
        // }
    },
}
</script>

<style lang="less">
.logo {
    display: flex;
    justify-content: center;
    margin-top: 80rpx;

    img {
        margin: 0 auto;
        width: 200rpx;
        height: 200rpx;
    }
}

.body {
    .bodyIn {
        display: flex;
        margin-top: 100rpx;
        margin: 35rpx auto;
        width: 654rpx;
        height: 88rpx;
        background: #eff0f3;
        line-height: 88rpx;
        border-right: 10rpx;
        line-height: 88rpx;

        .user {
            line-height: 88rpx;
            width: 654rpx;
            height: 88rpx;
        }

        img {
            position: relative;
            top: 20rpx;
            width: 50rpx;
            height: 50rpx;
            left: 30rpx;
        }
    }

    .password {
        margin: 35rpx auto;
        width: 654rpx;
        height: 88rpx;
        background: #eff0f3;
        line-height: 88rpx;
        border-right: 10rpx;
    }
}

.loging {
    margin-top: 50rpx;
    width: 654rpx;
    height: 94rpx;
    color: #ffffff;
    background: #0c69a4;
    border: 1px solid rgba(5, 5, 5, 0.08);
    border-radius: 23.5px;
}

.loging1 {
    justify-content: center;
    line-height: 94rpx;
    text-align: center;
    margin-top: 50rpx;
    margin-left: 47rpx;
    width: 654rpx;
    height: 94rpx;
    color: #ffffff;
    background: #0c69a4;
    border: 1px solid rgba(5, 5, 5, 0.08);
    border-radius: 23.5px;
}
</style>
